﻿using Microsoft.AspNetCore.Mvc;
using STF.Blog.Common;
using STF.Blog.IService;
using STF.Blog.WebApp.Areas.ForumManage.Filters;
using STF.Blog.WebApp.Areas.ForumManage.Models.ReleaseForm;
using X.PagedList;

namespace STF.Blog.WebApp.Areas.ForumManage.Controllers
{
    [Area("ForumManage")]
    [Login]
    public class ReleaseFormController : Controller
    {
        private IReleaseFormService _irfSvc;
        public ReleaseFormController(IReleaseFormService irfSvc)
        {
            _irfSvc = irfSvc;
        }

        [HttpGet]
        public async Task<IActionResult> Index(string search, int page = 1)
        {
            search = string.IsNullOrEmpty(search) ? "" : search;
            var data = await _irfSvc.GetByNameAsync(search);

            var RelFormList = data.Select(rf => new ReleaseFormListViewModel 
            {
                Id = rf.Id,
                Title = rf.Title,
                Details = rf.Details,
                CreateTime = rf.CreateTime,
                UpdateTime = rf.UpdateTime
            });

            ViewBag.Search = search;
            var pages = await RelFormList.ToPagedListAsync(page,PageConfig.PageSize);
            return View(pages);
        }

        [HttpGet]
        public async Task<IActionResult> Add() 
        {
            return View(new ReleaseFormAddViewModel());
        }

        [HttpPost]
        public async Task<IActionResult> Add(ReleaseFormAddViewModel model) 
        {
            if (ModelState.IsValid) 
            {
                await _irfSvc.AddRfAsync(model.Title,model.Details);
                return Redirect("~/ForumManage/ReleaseForm/Index");
            }
            return View(model);
        }

        [HttpGet]
        public async Task<IActionResult> Update(int id) 
        {
            var data = await _irfSvc.GetByIdAsync(id);
            return View(new ReleaseFormUpdateViewModel 
            {
                Id = data.Id,
                Title = data.Title,
                Details = data.Details
            });
        }

        [HttpPost]
        public async Task<IActionResult> Update(ReleaseFormUpdateViewModel model) 
        {
            if (ModelState.IsValid) 
            {
                await _irfSvc.UpdateRfAsync(model.Id,model.Title, model.Details);
                return Redirect("~/ForumManage/ReleaseForm/Index");
            }
            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> Delete(int id) 
        {
            await _irfSvc.PutTrashAsync(id);
            return Redirect("~/ForumManage/ReleaseForm/Index");
        }

    }
}
